<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="filterq.cate_id" placeholder="请选择分类" size="small">
            <el-option
              v-for="item in cateList"
              :key="item.id"
              :label="item.cate_name"
              :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="filterq.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="filterCate" size="small" >筛选</el-button>
            <el-button type="info" size="small"  @click="resetArt">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button @click="pubVisible = true" type="primary" size="small" class="btn-pub">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
      <el-table
      :data="artCateList"
      style="width: 100%">
      <el-table-column
        label="文章标题">
        <template v-slot="{ row }">
          <el-link @click="previewArt(row.id)" type="primary">{{row.title}}</el-link>
        </template>
      </el-table-column>
      <el-table-column
        prop="cate_name"
        label="文章分类">
      </el-table-column>
      <el-table-column
        label="发表时间">
        <template v-slot="scope">
          {{pubTime(scope.row.pub_date)}}
        </template>
      </el-table-column>
      <el-table-column
        prop="state"
        label="状态">
      </el-table-column>
      <el-table-column
        label="操作">
        <template v-slot='scope'>
        <el-button type="danger" size="mini"  @click="delArticle(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

      <!-- 分页区域 -->
      <div class="block" style="margin-top:15px">
        <!-- <span class="demonstration">完整功能</span> -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="q.pagenum"
          :page-sizes="[2, 3, 5, 10]"
          :page-size="q.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>

    </el-card>
    <!-- before-close 属性: 来设置关闭前的函数, 阻止关闭, 直到函数内调用 done 才会关闭 -->
    <!-- 发表文章的dialog -->
    <el-dialog
    @closed='$refs.pubForm.resetFields()'
      title="发表文章"
      :visible.sync="pubVisible"
      width="30%"
      fullscreen
      :before-close="handleClose">
      <el-form :model="pubForm" :rules="pubRules" ref="pubForm" label-width="100px" class="demo-pubForm">
        <el-form-item label="文章标题" prop="title">
          <el-input placeholder="请输入文章标题" v-model="pubForm.title"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select class="art-cate-sel" v-model="pubForm.cate_id" placeholder="请选择文章分类">
            <!-- value 要绑定 id, 这是提交给后台的 -->
            <el-option
              v-for="item in cateList"
              :key="item.id"
              :label="item.cate_name"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <quill-editor v-model="pubForm.content" @blur="$refs.pubForm.validateField('content')"></quill-editor>
          <!-- <p>你好</p> -->
        </el-form-item>

        <el-form-item label="文章封面" prop="cover_img">
        <!-- 用来显示封面的图片 -->
        <img v-if="coverPic" :src="coverPic" alt="" class="cover-img" ref="imgRef" />
        <img v-else src="../../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
        <br />
        <!-- 文件选择框，默认被隐藏 -->
        <input type="file" @change="choicePic" style="display: none;" accept="image/*" ref="iptFile" />
        <!-- 选择封面的按钮 -->
        <el-button type="text" @click="$refs.iptFile.click()">+ 选择封面</el-button>
      </el-form-item>
      <el-form-item prop="state">
        <el-button type="primary" @click="pubArt('已发布')">发布</el-button>
        <el-button type='info' @click="pubArt('草稿')">存为草稿</el-button>
      </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 预览的dialog -->
    <el-dialog title="文章预览" :visible.sync="previewVisible" width="80%">
  <h1 class="title">{{ getPreview.title }}</h1>

  <div class="info">
    <span>作者：{{ getPreview.nickname || getPreview.username }}</span>
    <span>发布时间：{{ pubTime(getPreview.pub_date)  }}</span>
    <span>所属分类：{{ getPreview.cate_name }}</span>
    <span>状态：{{ getPreview.state }}</span>
  </div>

  <!-- 分割线 -->
  <el-divider></el-divider>

  <!-- 文章的封面 -->
  <img :src="'http://www.liulongbin.top:3008' + getPreview.cover_img" alt="" />

  <!-- 文章的详情 -->
  <div v-html="getPreview.content" class="detail-box"></div>
</el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'

export default {
  name: 'ArtList',
  data() {
    return {
      pubVisible: false,
      previewVisible: false,
      coverPic: '',
      pubForm: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: '',
        state: ''
      },
      pubRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'blur' }
        ],
        cate_id: [{ required: true, message: '请选择文章分类', trigger: 'change' }],
        content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }],
        cover_img: [{ required: true, message: '请添加封面', trigger: 'change' }]
      },
      cateList: [],
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      artCateList: [],
      total: 0,
      filterq: {
        cate_id: '',
        state: ''
      },
      // 获取预览信息
      getPreview: {}
    }
  },
  methods: {
    // 参数1: done 是一个函数, 调用它可以关闭 dialog
    handleClose(done) {
      // 参数1: 内容
      // 参数2: 标题
      // 参数3: 配置对象, 可以设置 type
      this.$confirm('此操作将导致文章信息丢失, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(_ => {
          // 用户点击了确定
          // this.$refs.pubForm.resetFields()
          this.coverPic = ''
          done()
        })
        // 用户点击了取消
        .catch(_ => {})
    },
    async getCateList() {
      const { data: res } = await this.$http.get('/my/cate/list')
      // console.log(res)
      this.cateList = res.data
    },
    choicePic(e) {
      // console.log(e)
      const file = e.target.files[0]
      // console.log(file)
      // const url = URL.createObjectURL(file)
      // console.log(url)
      if (file) {
        this.coverPic = URL.createObjectURL(file)
        this.pubForm.cover_img = file
        this.$refs.pubForm.validateField('cover_img')
      } else {
        this.coverPic = ''
        this.pubForm.cover_img = ''
      }
    },
    pubArt(state) {
      this.$refs.pubForm.validate(async valid => {
        if (!valid) return
        this.pubForm.state = state
        const fd = new FormData()
        Object.keys(this.pubForm).forEach(k => fd.append(k, this.pubForm[k]))
        const { data: res } = await this.$http.post('/my/article/add', fd)
        // console.log(res)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)

        // 关闭dialog
        this.pubVisible = false
        this.coverPic = ''
        this.getArtCateList()
      })
    },
    async getArtCateList() {
      const { data: res } = await this.$http.get('/my/article/list', { params: this.q })
      // console.log(res)
      this.artCateList = res.data
      this.total = res.total
    },
    handleSizeChange(e) {
      // console.log(e)
      this.q.pagesize = e
      this.getArtCateList()
    },
    handleCurrentChange(e) {
      // console.log(e)
      this.q.pagenum = e
      this.getArtCateList()
    },
    pubTime(row) {
      // console.log(row)
      // const dayjs = require('dayjs')
      // console.log(dayjs(row.pub_date).format('YYYY-MM-DD HH:mm:ss'))
      return dayjs(row).format('YYYY-MM-DD HH:mm:ss')
    },
    async delArticle(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const { data: res } = await this.$http.delete('/my/article/info', { params: { id } })
        // console.log(res)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)

        // 在当前页数据 artCateList.length === 1 时而不是 === 0  , 才会进入判断
        // 因为先删除的是后台数据 , 本地数据没有更新 , 而本地的 artCateList.length 仍显示还有一条
        // 所以此时的判断条件是 artCateList.length === 1
        // 只有在pagenum>1的时候 , 才需要pagenum-- , 当只有一条数据的时候 , pagenum就是第一页
        // 当pagenum==1时,就不会进if判断
        if (this.artCateList.length === 1 && this.q.pagenum > 1) {
          this.q.pagenum--
        }
        this.getArtCateList()
      }).catch(() => {})
    },
    filterCate() {
      this.q.pagenum = 1
      this.q.cate_id = this.filterq.cate_id
      this.q.state = this.filterq.state
      this.getArtCateList()
    },
    resetArt() {
      this.filterq = {
        cate_id: '',
        state: ''
      }
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      this.getArtCateList()
    },
    async  previewArt(id) {
      const { data: res } = await this.$http.get('/my/article/info', { params: { id } })
      // console.log(res)
      this.getPreview = res.data
      this.previewVisible = true
    }
  },
  created() {
    this.getCateList()
    this.getArtCateList()
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
.art-cate-sel.el-select {
  width: 100%
}

// scoped 作用: 让 style 中的选择器只对当前 template 中的标签生效
// 原理:
// 1. 给所有的标签添加一个 data-v-hash
// 注意事项: scoped 只会给当前 template 中出现的标签添加 data-v-hash, 如果是组件, 则只会给组件的根标签添加 data-v-hash, 其中的子元素不会加
// 2. 给所有的选择器加一个属性交集选择器
// 问题原因: 内部标签没有 data-v-hash 属性, 而 style 中的选择器都有属性交集选择器, 所以无法选中组件内部的标签
// 解决方案: 深度选择器
// 原理: 将以前的交集选择器(.ql-editor[data-v-hash]) 改为后代选择器([data-v-hash] .ql-editor)
/deep/ .quill-editor .ql-editor {
  height: 300px
}

.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}

.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}

// 修改 dialog 内部元素的样式，需要添加样式穿透
/deep/ .detail-box {
  img {
    width: 500px;
  }
}
</style>
